<template>
  <div class="roles-page">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-button type="primary" @click="showDialog('添加角色')"
        >添加角色</el-button
      >
      <el-table :data="rolesList" border stripe>
        <el-table-column type="expand">
          <template #default="{ row }">
            <el-row
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '']"
              v-for="(item1, i1) in row.children"
              :key="item1.id"
            >
              <el-col :span="5">
                <el-tag closable @close="delRolesId(row, item1.id)">
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="delRolesId(row, item2.id)"
                    >
                      {{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="delRolesId(row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag></el-col
                  >
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" width="50"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作" width="300px">
          <template #default="{ row }">
            <div class="actions">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="small"
                @click="showDialog('修改角色', row.id)"
                >编辑</el-button
              >
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="small"
                @click="delRoles(row.id)"
                >删除</el-button
              >
              <el-button
                type="warning"
                icon="el-icon-menu"
                size="small"
                @click="isShowRolesDialog(row)"
                >分配权限
              </el-button>
            </div>
          </template></el-table-column
        >
      </el-table>
    </el-card>
    <el-dialog
      :title="title"
      :visible.sync="addRolesVisible"
      width="50%"
      @close="addClose"
    >
      <el-form
        :model="addForm"
        :rules="addRules"
        ref="addForm"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoless">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="分配权限"
      :visible.sync="showRolesDialog"
      width="50%"
      @close="isRightsDialogClose"
    >
      <el-tree
        :data="rightsList"
        show-checkbox
        :props="treeProps"
        node-key="id"
        default-expand-all
        :default-checked-keys="defkeys"
        ref="treeRef"
      >
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showRolesDialog = false">取 消</el-button>
        <el-button type="primary" @click="checkRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  addRoles,
  delRolesByid,
  delRolesId,
  editRoles,
  getAllRightsList,
  getRolesId,
  getRolesList,
  updateAllRights,
} from "@/api/roles";
export default {
  name: "roleList",
  data() {
    return {
      addRolesVisible: false,
      showRolesDialog: false,
      title: "添加角色",
      rolId: "",
      rolesList: [],
      rightsList: [],
      defkeys: [],
      addForm: {
        roleName: "",
        roleDesc: "",
      },
      addRules: {
        roleName: [
          {
            required: true,
            message: "请输入角色名称",
            trigger: "blur",
          },
        ],
        roleDesc: [
          {
            required: true,
            message: "请输入角色描述",
            trigger: "blur",
          },
        ],
      },
      treeProps: {
        children: "children",
        label: "authName",
      },
    };
  },
  created() {
    this.getRolesLists();
  },
  methods: {
    async getRolesLists() {
      const res = await getRolesList();
      // console.log(res);
      if (res.meta.status === 200) {
        this.rolesList = res.data;
      } else {
        this.$message.error("获取失败");
      }
    },
    addClose() {
      this.$refs.addForm.resetFields();
    },
    async showDialog(type, id) {
      this.title = type;
      this.addRolesVisible = true;
      if (type !== "添加角色") {
        const res = await getRolesId(id);
        // console.log(res);
        this.addForm = {
          ...res.data,
        };
      }
    },
    async addRoless() {
      await this.$refs.addForm.validate();
      try {
        if (this.title === "添加角色") {
          const res = await addRoles(this.addForm);
          if (res.meta.status === 201) {
            this.$message.success("添加角色成功");
          } else {
            this.$message.error(res.meta.msg);
          }
        }
        if (this.title === "修改角色") {
          const { roleName, roleDesc } = this.addForm;
          console.log(this.addForm.roleId);
          const res = await editRoles(this.addForm.roleId, {
            roleName,
            roleDesc,
          });
          // console.log(res);
          if (res.meta.status === 201) {
            this.$message.success("修改角色成功");
          } else {
            this.$message.error(res.meta.msg);
          }
        }
      } catch (err) {
        this.$message.error("操作失败");
      }
      this.getRolesLists();
      this.$refs.addForm.resetFields();
      this.addRolesVisible = false;
    },
    async delRoles(id) {
      const resConfrm = await this.$confirm(
        "此操作将删除该角色, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (resConfrm !== "confirm") {
        return this.$message.info("已取消删除");
      }
      const res = await delRolesId(id);
      if (res.meta.status === 200) {
        this.$message.success("删除成功");
        this.getRolesLists();
      } else {
        this.$message.error(res.meta.msg);
      }
      this.getRolesLists();
    },
    async delRolesId(row, RigId) {
      const resConfrm = await this.$confirm(
        "此操作将删除该角色, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (resConfrm !== "confirm") {
        return this.$message.info("已取消删除");
      }
      const res = await delRolesByid(row.id, RigId);
      // console.log(res);
      if (res.meta.status === 200) {
        this.$message.success("删除成功");
        row.children = res.data;
      } else {
        this.$message.error(res.meta.msg);
      }
      row.children = res.data;
    },
    async isShowRolesDialog(row) {
      this.showRolesDialog = true;
      this.rolId = row.id;
      const res = await getAllRightsList();
      if (res.meta.status === 200) {
        this.rightsList = res.data;
        this.getDefKey(row, this.defkeys);
      } else {
        this.$message.error("获取失败");
      }
    },
    getDefKey(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => {
        this.getDefKey(item, arr);
      });
    },
    isRightsDialogClose() {
      this.defkeys = [];
    },
    async checkRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      // console.log(keys);
      const strKeys = keys.join(",");
      const res = await updateAllRights(this.rolId, strKeys);
      console.log(res);
      if (res.meta.status === 200) {
        this.$message.success("权限分配成功");
      } else {
        this.$message.error(res.meta.msg);
      }
      this.getRolesLists();
      this.showRolesDialog = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.el-breadcrumb {
  margin-bottom: 15px;
}
.el-button {
  margin-bottom: 15px;
}
.el-row {
  margin-left: 60px;
  display: flex;
  align-items: center;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.bdtop {
  border-top: 1px solid #eee;
}
.el-tag {
  margin: 7px;
}
</style>
